<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Template;
use Storage;

class TemplateController extends Controller
{

    public function index()
    {
        $user = \Auth::user();
        return view('admin/manage_template', compact("user"))->withTemplates(Template::orderBy('updated_at', 'desc')->get());
    }

    public function create()
    {
        $user = \Auth::user();
        return view('admin/create_template', compact("user"));
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'title' => 'required|unique:articles|max:255',
            'template' => 'required',
        ]);

        if ($request->isMethod('post')) {

            $file = $request->file('template');

            // 文件是否上传成功
            if ($file->isValid()) {

                // 获取文件相关信息
                $originalName = $file->getClientOriginalName(); // 文件原名
                $ext = $file->getClientOriginalExtension();     // 扩展名
                $realPath = $file->getRealPath();   //临时文件的绝对路径
                $type = $file->getClientMimeType();     // image/jpeg

                // 上传文件
                $filename = substr($originalName, 0, strlen($originalName) - strlen($ext) - 1) . '_' . date('Y-m-d-H-i-s') . '-' . '.' . $ext;
                // 使用我们新建的uploads本地存储空间（目录）
                $bool = Storage::disk('templates')->put($filename, file_get_contents($realPath));
                if ($bool) {
                    $template = new Template;
                    $template->title = $request->get('title');
                    $template->body = $filename;

                    if ($template->save()) {
                        return redirect('template');
                    }
                }

            }

        }

        return redirect()->back()->withInput()->withErrors('提交失败！');


    }

    public function destroy($id)
    {
        $template = Template::find($id);
        Storage::disk('uploads')->delete($template->body);
        Template::find($id)->delete();
        return redirect()->back()->withInput()->withErrors('删除成功！');
    }

    public function show($id) {
        $user = \Auth::user();
        $template = Template::find($id);

        if ($user->role == 1) {
            return view('student/show_template', compact("user", "template"));
        } else if ($user->role == 2) {
            return view('supervisor/show_template', compact("user", "template"));
        } else if ($user->role == 3) {
            return view('admin/show_template', compact("user", "template"));
        }
    }

}
